package com.yhy.auth.extension.sms;

import com.yhy.common.security.service.MyUserDetailsService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 短信验证码认证授权提供者
 */
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    private MyUserDetailsService userDetailsService;

    public SmsCodeAuthenticationProvider(MyUserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    public SmsCodeAuthenticationProvider() {
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication;
        String mobile = (String) authenticationToken.getPrincipal();
        String code = (String) authenticationToken.getCredentials();
        UserDetails userDetails = userDetailsService.loadUserByMobile(mobile);
        SmsCodeAuthenticationPreProcessor.doHandler(mobile, code);
        SmsCodeAuthenticationToken result = new SmsCodeAuthenticationToken(userDetails,
                authentication.getCredentials(), userDetails.getAuthorities());
        result.setDetails(authentication.getDetails());
        return result;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
